<template>
  <nav>
    <aside>
      <!-- <el-button circle>
        <el-icon :size="22"><ArrowLeft /></el-icon>
      </el-button>
      <article>第 16 周</article>
      <el-button circle>
        <el-icon :size="22"><ArrowRight /></el-icon>
      </el-button> -->
    </aside>
    <section v-if="userStore.isAdmin === 1">
      <el-button type="success" icon="Plus" @click="onAdd">添加课程</el-button>
      <el-button type="primary" icon="Edit" @click="onEidt">修改课程</el-button>
      <el-button type="danger" icon="Minus" @click="onDelete">删除课程</el-button>
    </section>
  </nav>
  <!-- 抽屉 -->
  <el-drawer v-model="isShowDrawer" custom-class="drawer" :before-close="onBeforeClose" size="90%" :destroy-on-close="true" @closed="onClosed">
    <template #header>
      <h4 class="drawer-header" v-html="title"></h4>
    </template>
    <template #default>
      <div class="drawer-content">
        <section v-if="isShowForm">
          <el-form ref="formRef" :inline="true" :model="courseData" :rules="rules" label-width="80px">
            <el-form-item label="课程名" prop="courseName">
              <el-input v-model="courseData.courseName" placeholder="请输入课程名称" clearable />
            </el-form-item>
            <el-form-item label="地点" prop="place">
              <el-input v-model="courseData.place" placeholder="请输入上课地点" clearable />
            </el-form-item>
            <el-form-item label="展示颜色" prop="color">
              <el-radio-group v-model="radioValue">
                <el-radio label="defalut" border>系统默认</el-radio>
                <el-radio label="custom" border>自定义</el-radio>
              </el-radio-group>
              <el-color-picker v-model="courseData.color" :predefine="colorList" :disabled="radioValue !== 'custom'" />
            </el-form-item>
          </el-form>
        </section>

        <course-table
          class="table-box"
          :data="tableData"
          :open-type="openType"
          @on-td-click="onTdCilck"
          @on-course-click="onCourseClick"
        ></course-table>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="isShowDrawer = false">取 消</el-button>
        <el-button type="primary" @click="confirmClick">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import courseTable, { courseTableType } from '../../../../components/courseTable/Index.vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { APIData, IActiveCourseList, IActiveTdList, IAllCourseParams, ICourseTable, IEditCourse } from '../../../../type';
import { useUserStore } from '../../../../store/user';
import { useAPI } from '../../../../request/api';
const userStore = useUserStore();
const api = useAPI();

interface IProps {
  data: ICourseTable[];
}

const props = defineProps<IProps>();
const tableData = ref(props.data);
const isShowDrawer = ref<boolean>();
const radioValue = ref<string>('defalut');
const formRef = ref<FormInstance>();
const openType = ref(courseTableType.default);
let activeTdList = [] as IActiveTdList[];
const activeCourseList = ref<IActiveCourseList[]>();
const courseData = ref({} as ICourseTable);
const colorList = ['#ff8c94', '#ffd3b6', '#a3de83', '#cca8e9', '#70a1d7', '#ed93cb', '#2eb872', '#6eb6ff'];
const rules = {
  courseName: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 2, message: '最少两个字符', trigger: 'blur' },
  ],
  place: [
    { required: true, message: '必填项', trigger: 'blur' },
    { min: 2, message: '最少两个字符', trigger: 'blur' },
  ],
};

watch(isShowDrawer, () => {
  if (isShowDrawer) courseData.value.color = getRandomColor();
});
watch(
  () => props.data,
  newValue => {
    tableData.value = newValue;
  }
);

const title = computed(() => {
  if (openType.value === 'add') return '添加课程 (请下方课表中点击无课程安排的表格以确定添加的课程时间)';
  if (openType.value === 'edit') return '修改课程 (请在下方课表中点击要修改的课程)';
  if (openType.value === 'delete') return '删除课程 (请在下方课表中点击要删除的课程(支持多选))';
});
const isShowForm = computed(() => {
  if (openType.value === 'delete') return false;
  if (openType.value === 'add') return true;
  if (openType.value === 'edit') {
    if (courseData.value.courseName !== undefined) return true;
    else return false;
  }
});

const getRandomColor = () => {
  let colorRandom = Math.floor(Math.random() * colorList.length + 1) - 1;
  let color;
  for (let i = 0; colorList.length > i; i++) {
    if (i == colorRandom) {
      color = colorList[i];
    }
  }
  return color;
};

const getAllTchTableData = async () => {
  const params: IAllCourseParams = { stage: userStore.currentStage, department: userStore.currentDepartment };
  const res: APIData = await api.findAllByPost(params, 'student', 'courseTable');
  if (res.code === 200) tableData.value = res.data.rows;
  else ElMessage.error(res.message);
  // console.log(res);
  return res.code;
};

const onAdd = async () => {
  await getAllTchTableData();
  openType.value = courseTableType.add;
  isShowDrawer.value = true;
};
const onEidt = () => {
  openType.value = courseTableType.edit;
  isShowDrawer.value = true;
};
const onDelete = () => {
  openType.value = courseTableType.delete;
  isShowDrawer.value = true;
};

const confirmClick = async () => {
  if (openType.value === 'delete') await deleteCourseTables();

  const formEl = formRef.value;
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      if (openType.value === 'add') await addCourseTables();
      if (openType.value === 'edit') await editCourseTable();
    }
  });
};

const emit = defineEmits(['onReGetData']);
const addCourseTables = async () => {
  const allCourse = buildNewCourse();
  // console.log(allCourse);
  const addCourseList = allCourse?.map(item => {
    const course = {} as ICourseTable;
    course.courseName = courseData.value.courseName;
    course.workId = userStore.userInfo.workId;
    course.tchName = userStore.userInfo.name;
    course.weekDay = item.weekDay;
    course.orderNum = item.orderNum;
    course.smallCount = item.smallCount;
    course.place = courseData.value.place;
    course.stage = userStore.currentStage;
    course.department = userStore.currentDepartment;
    course.color = courseData.value.color;
    return course;
  });

  if (!addCourseList) {
    ElMessage.error('网络开了小差，请重新选择');
    return;
  }
  const res: APIData = await api.save(addCourseList, userStore.role, 'addCourseTables');
  if (res.code === 200) {
    ElMessage.success('添加成功');
    emit('onReGetData');
    isShowDrawer.value = false;
  } else ElMessage.error(res.message);
};

const editCourseTable = async () => {
  const editCourse: IEditCourse = {
    id: courseData.value.id as string,
    courseName: courseData.value.courseName,
    place: courseData.value.place,
    color: courseData.value.color,
  };
  const res: APIData = await api.save(editCourse, userStore.role, 'modifyCourseTable');
  if (res.code === 200) {
    ElMessage.success('修改成功');
    emit('onReGetData');
    isShowDrawer.value = false;
  } else ElMessage.error(res.message);
};

const deleteCourseTables = async () => {
  if (!activeCourseList.value) {
    ElMessage.error('暂未选择任何课程');
    return;
  }

  ElMessageBox.confirm('您将永久地删除该课程信息,是否继续?', '提 示', { type: 'warning' })
    .then(async () => {
      const deleteIdList = activeCourseList.value?.map(item => {
        return item.course.id;
      });

      const res: APIData = await api.trueDelete(deleteIdList as string[], userStore.role, 'courseTable');
      if (res.code === 200) {
        ElMessage.success('删除成功');
        emit('onReGetData');
        isShowDrawer.value = false;
      } else ElMessage.error(res.message);
    })
    .catch(() => {});
};

const onBeforeClose = (done: () => void) => {
  ElMessageBox.confirm('关闭该页面后数据会清空,确定继续吗?', '提示', { type: 'warning' })
    .then(() => {
      done(); //关抽屉
    })
    .catch(() => {});
};

const onClosed = () => {
  courseData.value = {} as ICourseTable; //清数据
  const formEl = formRef.value;
  if (formEl) formEl.clearValidate(); //清验证
};

const onTdCilck = (list: IActiveTdList[]) => {
  activeTdList = list;
};

const onCourseClick = (list: IActiveCourseList[]) => {
  activeCourseList.value = list;
  //深拷贝，否则courseData改变时，会同步更改表格中选中课程的数据
  if (openType.value === 'edit') courseData.value = JSON.parse(JSON.stringify(list[0].course));
  // console.log(activeCourseList.value);
};

interface IAllCourse {
  weekDay: number;
  orderNum: number;
  smallCount: number;
}
const buildNewCourse = () => {
  if (activeTdList.length === 0) {
    ElMessage.error('请在下方课表中点击选中课程时间');
    return;
  }
  // console.log(activeTdList);
  let currentColNum: number;
  let allCourse = [] as IAllCourse[];
  const tempTd = JSON.parse(JSON.stringify(activeTdList));
  // tempTd.sort((a: any, b: any) => a.colNum - b.colNum);

  let usedCols = [] as number[];
  for (let i = 0; i < tempTd.length; i++) {
    currentColNum = tempTd[i].colNum;

    let flag = false;
    for (const usedCol of usedCols) {
      if (currentColNum === usedCol) {
        flag = true;
        break;
      }
    }
    if (flag) continue;
    else usedCols.push(currentColNum);

    let sameColItems = tempTd.filter((item: any) => {
      if (item.colNum === currentColNum) return item;
    });
    sameColItems.sort((a: any, b: any) => a.rowNum - b.rowNum);

    allCourse = findCourses(sameColItems, allCourse);
  }
  return allCourse;
  // console.log(allCourse);
};

const findCourses = (list: any[], allCourse: any[]) => {
  let perColCourse = {} as any;

  for (const index in list) {
    const currentItem = list[index];
    const nextItem = list[Number(index) + 1];
    if (nextItem) {
      if (nextItem.rowNum !== currentItem.rowNum + 1) {
        perColCourse.smallCount = Number(index) + 1;
        perColCourse.weekDay = list[0].colNum;
        perColCourse.orderNum = list[0].rowNum;
        allCourse.push(perColCourse);
        const res: any[] = findCourses(list.slice(Number(index) + 1), allCourse);
        return res;
      }
    } else {
      perColCourse.smallCount = list.length;
      perColCourse.weekDay = list[0].colNum;
      perColCourse.orderNum = list[0].rowNum;
      allCourse.push(perColCourse);
      return allCourse;
    }
  }
  return []; //正常情况不会走这里
};

// defineExpose({
//   isShowDrawer,
// });
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 8px;
}
nav {
  padding: 0 16px;
  height: 60px;
  display: flex;
  justify-content: space-between;

  aside {
    flex: 1;
    display: flex;
    align-items: center;
    article {
      font-size: 18px;
      font-weight: bold;
      margin: 0 8px;
    }
    .el-button {
      height: 60px;
      margin-left: 0 !important;
      background-color: transparent;
      transform: scale(0.7);
      box-shadow: 0 0 12px 2px rgba(0, 0, 0, 0.1);
    }
    .el-icon {
      color: var(--font-color);
    }
  }
  section {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    // padding-right: 16px;
  }
}

.drawer {
  .drawer-header {
    font-size: 18px;
    color: var(--font-color);
  }
  .drawer-content {
    height: 100%;
    display: flex;
    justify-content: space-around;
    flex-direction: column;

    section {
      display: flex;
      justify-content: space-between;
    }

    .table-box {
      height: calc(100% - 80px);
    }

    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }
}
</style>
